#ifndef _THREAD_LOCK_H_
#define _THREAD_LOCK_H_

#pragma once
#include <windows.h>

class InstanceLock;

class InstanceLockBase
{
	friend class InstanceLock;

	CRITICAL_SECTION cs;

	void Lock()
	{
		::EnterCriticalSection(&cs);
	}

	void Unlock()
	{
		::LeaveCriticalSection(&cs);
	}

public:
	InstanceLockBase()
	{
		::InitializeCriticalSection(&cs);
	}

	~InstanceLockBase()
	{
		::DeleteCriticalSection(&cs);
	}
};

class InstanceLock
{
private:
	InstanceLockBase* _pObj;

public:
	InstanceLock(InstanceLockBase* pObj)
	{
		_pObj = pObj;

		if(NULL != _pObj)
        {
			_pObj->Lock();
        }
	}

	~InstanceLock()
	{
        try
        {
		    if(NULL != _pObj)
            {
			    _pObj->Unlock();
            }
        }
        catch(...)
        {
            return;
        }
	}

private:
    InstanceLock()
    {
        return;
    }
};

#endif //_THREAD_LOCK_H_
